﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Outpatient.Doman.Hospitalization;
using Outpatient.Doman.Smart;
using Outpatient.Doman.SmartClinic;
using Outpatient.ErrorCode;
using Outpatient.Infrastructure;
using OutpatientApi.DTO;
using OutpatientApi.Methodimplementation.IServices;
using System.ComponentModel.DataAnnotations;

namespace OutpatientApi.Methodimplementation.Services
{
    /// <summary>
    /// 住院管理实体类
    /// </summary>
    public class InpatientManagement : IInpatientManagement
    {
        private readonly EFDbContext _context;
        private readonly ILogger<InpatientManagement> _logger;
        private readonly IBaseRepository<RoomType> roomType;
        private readonly IBaseRepository<HospitalBed> hospitalBed;
        private readonly IBaseRepository<Room> roominfo;
        private readonly IBaseRepository<PatientAdmission> patientAdmission;
        private readonly IBaseRepository<DepartmentInfo> departmentInfo;
        private readonly IBaseRepository<MedicalCardRegistration> medicalCardRegistration;
        private readonly IBaseRepository<Fee> frrinfo;
        private readonly IBaseRepository<Medicine> medicine;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="logger">日志记录器</param>
        public InpatientManagement(EFDbContext context, ILogger<InpatientManagement> logger,
            IBaseRepository<RoomType> roomType,
            IBaseRepository<HospitalBed> hospitalBed,
            IBaseRepository<Room> roominfo,
            IBaseRepository<PatientAdmission> patientAdmission,
            IBaseRepository<DepartmentInfo> DepartmentInfo,
            IBaseRepository<MedicalCardRegistration> medicalCardRegistration,IBaseRepository<Fee> frrinfo,
            IBaseRepository<Medicine> medicine)
        {
            _context = context;
            _logger = logger;
            this.roomType = roomType;
            this.hospitalBed = hospitalBed;
            this.roominfo = roominfo;
            this.patientAdmission = patientAdmission;
            departmentInfo = DepartmentInfo;
            this.medicalCardRegistration = medicalCardRegistration;
            this.frrinfo = frrinfo;
            this.medicine = medicine;
        }

        /// <summary>
        /// 批量添加病房
        /// </summary>
        /// <param name="batchAddDto">批量添加病房参数</param>
        /// <returns>批量添加结果</returns>
        public async Task<ApiResult<List<int>>> BatchAddRoomsAsync(BatchAddRoomDto batchAddDto)
        {
            try
            {
                // 记录批量添加开始日志
                _logger.LogInformation("开始批量添加病房，数量：{RoomCount}", batchAddDto.Rooms.Count);

                // 参数验证
                var validationResults = new List<ValidationResult>();
                var validationContext = new ValidationContext(batchAddDto);
                if (!Validator.TryValidateObject(batchAddDto, validationContext, validationResults, true))
                {
                    var errorMessage = string.Join("; ", validationResults.Select(v => v.ErrorMessage));
                    _logger.LogWarning("批量添加病房失败：参数验证失败 - {ErrorMessage}", errorMessage);
                    return new ApiResult<List<int>> { msg = errorMessage };
                }

                // 验证每个病房的数据
                var invalidRooms = new List<string>();
                var roomNumbers = new HashSet<string>();

                foreach (var room in batchAddDto.Rooms)
                {
                    // 验证单个病房数据
                    var roomValidationResults = new List<ValidationResult>();
                    var roomValidationContext = new ValidationContext(room);
                    if (!Validator.TryValidateObject(room, roomValidationContext, roomValidationResults, true))
                    {
                        invalidRooms.Add($"病房 {room.RoomNumber}: {string.Join("; ", roomValidationResults.Select(v => v.ErrorMessage))}");
                        continue;
                    }

                    // 检查病房编号是否重复
                    if (roomNumbers.Contains(room.RoomNumber))
                    {
                        invalidRooms.Add($"病房 {room.RoomNumber}: 病房编号重复");
                        continue;
                    }
                    roomNumbers.Add(room.RoomNumber);

                    // 检查病房编号是否已存在于数据库
                    var existingRoom = await _context.Rooms
                        .FirstOrDefaultAsync(r => r.RoomNumber == room.RoomNumber && !r.IsDelete);

                    if (existingRoom != null)
                    {
                        invalidRooms.Add($"病房 {room.RoomNumber}: 病房编号已存在");
                        continue;
                    }

                    // 验证科室是否存在
                    var department = await _context.DepartmentInfos
                        .FirstOrDefaultAsync(d => d.DepartmentId == room.DepartmentId && !d.IsDelete);

                    if (department == null)
                    {
                        invalidRooms.Add($"病房 {room.RoomNumber}: 科室不存在，科室ID：{room.DepartmentId}");
                        continue;
                    }

                    // 验证病房类型是否存在
                    var roomType = await _context.RoomTypes
                        .FirstOrDefaultAsync(rt => rt.RoomTypeId == room.RoomTypeId && !rt.IsDelete);

                    if (roomType == null)
                    {
                        invalidRooms.Add($"病房 {room.RoomNumber}: 病房类型不存在，类型ID：{room.RoomTypeId}");
                        continue;
                    }
                }

                // 如果有验证失败的病房，返回错误信息
                if (invalidRooms.Any())
                {
                    var errorMessage = string.Join("; ", invalidRooms);
                    _logger.LogWarning("批量添加病房失败：数据验证失败 - {ErrorMessage}", errorMessage);
                    return new ApiResult<List<int>> { msg = errorMessage };
                }

                // 批量添加病房
                var roomsToAdd = new List<Room>();

                foreach (var roomDto in batchAddDto.Rooms)
                {
                    var room = new Room
                    {
                        RoomNumber = roomDto.RoomNumber,
                        Floor = roomDto.Floor,
                        DepartmentId = roomDto.DepartmentId,
                        RoomTypeId = roomDto.RoomTypeId,
                        Number_beds = roomDto.Number_beds,
                        Price = roomDto.Price,
                        CreatedAt = DateTime.Now,
                        IsDelete = false
                    };

                    roomsToAdd.Add(room);
                }

                // 使用执行策略进行批量添加
                var addedRoomIds = new List<int>();
                var executionStrategy = _context.Database.CreateExecutionStrategy();

                await executionStrategy.ExecuteAsync(async () =>
                {
                    using var transaction = await _context.Database.BeginTransactionAsync();
                    try
                    {
                        _logger.LogInformation("开始数据库事务，准备添加 {Count} 个病房", roomsToAdd.Count);

                        // 逐个添加病房，避免批量操作可能的问题
                        foreach (var room in roomsToAdd)
                        {
                            _context.Rooms.Add(room);
                            await _context.SaveChangesAsync();
                            addedRoomIds.Add(room.RoomId);
                            
                            _logger.LogInformation("成功添加病房：ID={RoomId}, 编号={RoomNumber}", room.RoomId, room.RoomNumber);
                        }

                        await transaction.CommitAsync();

                        // 记录批量添加成功日志
                        _logger.LogInformation("批量添加病房成功，添加数量：{AddedCount}，病房ID：{RoomIds}", 
                            addedRoomIds.Count, string.Join(",", addedRoomIds));
                    }
                    catch (Exception ex)
                    {
                        await transaction.RollbackAsync();
                        _logger.LogError(ex, "批量添加病房失败：数据库操作异常 - {ErrorMessage}", ex.Message);
                        throw;
                    }
                });

                var apiResult = new ApiResult<List<int>>();
                apiResult.success(addedRoomIds, $"批量添加病房成功，共添加 {addedRoomIds.Count} 个病房");
                return apiResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量添加病房失败：系统异常 - {ErrorMessage}", ex.Message);
                return new ApiResult<List<int>> { msg = $"批量添加病房失败：系统异常 - {ex.Message}" };
            }
        }

        /// <summary>
        /// 添加单个病房
        /// </summary>
        /// <param name="addDto">添加病房参数</param>
        /// <returns>添加结果</returns>
        public async Task<ApiResult<int>> AddRoomAsync(AddRoomDto addDto)
        {
            try
            {
                // 记录添加开始日志
                _logger.LogInformation("开始添加病房，病房编号：{RoomNumber}", addDto.RoomNumber);

                // 参数验证
                var validationResults = new List<ValidationResult>();
                var validationContext = new ValidationContext(addDto);
                if (!Validator.TryValidateObject(addDto, validationContext, validationResults, true))
                {
                    var errorMessage = string.Join("; ", validationResults.Select(v => v.ErrorMessage));
                    _logger.LogWarning("添加病房失败：参数验证失败 - {ErrorMessage}", errorMessage);
                    return new ApiResult<int> { msg = errorMessage };
                }

                // 检查病房编号是否已存在
                var existingRoom = await _context.Rooms
                    .FirstOrDefaultAsync(r => r.RoomNumber == addDto.RoomNumber && !r.IsDelete);

                if (existingRoom != null)
                {
                    _logger.LogWarning("添加病房失败：病房编号已存在，病房编号：{RoomNumber}", addDto.RoomNumber);
                    return new ApiResult<int> { msg = "病房编号已存在" };
                }

                // 验证科室是否存在
                var department = await _context.DepartmentInfos
                    .FirstOrDefaultAsync(d => d.DepartmentId == addDto.DepartmentId && !d.IsDelete);

                if (department == null)
                {
                    _logger.LogWarning("添加病房失败：科室不存在，科室ID：{DepartmentId}", addDto.DepartmentId);
                    return new ApiResult<int> { msg = "科室不存在" };
                }

                // 验证病房类型是否存在
                var roomType = await _context.RoomTypes
                    .FirstOrDefaultAsync(rt => rt.RoomTypeId == addDto.RoomTypeId && !rt.IsDelete);

                if (roomType == null)
                {
                    _logger.LogWarning("添加病房失败：病房类型不存在，类型ID：{RoomTypeId}", addDto.RoomTypeId);
                    return new ApiResult<int> { msg = "病房类型不存在" };
                }

                // 创建病房实体
                var room = new Room
                {
                    RoomNumber = addDto.RoomNumber,
                    Floor = addDto.Floor,
                    DepartmentId = addDto.DepartmentId,
                    RoomTypeId = addDto.RoomTypeId,
                    Number_beds = addDto.Number_beds,
                    Price = addDto.Price,
                    CreatedAt = DateTime.Now,
                    IsDelete = false
                };

                // 添加到数据库
                _context.Rooms.Add(room);
                await _context.SaveChangesAsync();

                // 记录添加成功日志
                _logger.LogInformation("病房添加成功，病房ID：{RoomId}，病房编号：{RoomNumber}", 
                    room.RoomId, addDto.RoomNumber);

                var apiResult = new ApiResult<int>();
                apiResult.success(room.RoomId, "病房添加成功");
                return apiResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加病房失败：系统异常 - {ErrorMessage}", ex.Message);
                return new ApiResult<int> { msg = $"添加病房失败：系统异常 - {ex.Message}" };
            }
        }
        /// <summary>
        /// 查找病房类型信息
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<RoomType>>> GetRoomType()
        {
            try
            {
                var res = new ApiResult<List<RoomType>>();


                var info = roomType.Getlist().Where(x => x.IsDelete.Equals(false));

                res.success(info.ToList(), "查找病房类型信息成功");
                return res;


            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 查找病床号类型信息
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<HospitalBed>>> GetHospitalBed()
        {
            try
            {
                var res = new ApiResult<List<HospitalBed>>();
                var info = hospitalBed.Getlist().Where(x => x.IsDelete.Equals(false));

                res.success(info.ToList(), "查找病房类型信息成功");
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查找房间号
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<RoomDataDto>>> SearchRoomData()
        {
            try
            {
                var res = new ApiResult<List<RoomDataDto>>();


                var info = roominfo.Getlist().Where(x => x.IsDelete.Equals(false)).Select(x => new RoomDataDto()
                {
                    RoomId= x.RoomId,
                    RoomNumber= x.RoomNumber

                }).ToList();

                res.success(info.ToList(), "查找病房类型信息成功");
                return res;

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加患者住院登记
        /// </summary>
        /// <param name="addDto">添加患者住院登记参数</param>
        /// <returns>添加结果</returns>
        public async Task<ApiResult<int>> AddPatientAdmissionAsync(AddPatientAdmissionDto addDto)
        {
            try
            {
                // 记录添加开始日志
                _logger.LogInformation("开始添加患者住院登记，患者卡号：{Patient}", addDto.Patient);

                // 参数验证
                var validationResults = new List<ValidationResult>();
                var validationContext = new ValidationContext(addDto);
                if (!Validator.TryValidateObject(addDto, validationContext, validationResults, true))
                {
                    var errorMessage = string.Join("; ", validationResults.Select(v => v.ErrorMessage));
                    _logger.LogWarning("添加患者住院登记失败：参数验证失败 - {ErrorMessage}", errorMessage);
                    return new ApiResult<int> { msg = errorMessage };
                }

                // 验证科室是否存在
                var department = await _context.DepartmentInfos
                    .FirstOrDefaultAsync(d => d.DepartmentId == addDto.DepartmentId && !d.IsDelete);

                if (department == null)
                {
                    _logger.LogWarning("添加患者住院登记失败：科室不存在，科室ID：{DepartmentId}", addDto.DepartmentId);
                    return new ApiResult<int> { msg = "科室不存在" };
                }

                // 验证病房是否存在
                var room = await _context.Rooms
                    .FirstOrDefaultAsync(r => r.RoomId == addDto.RoomId && !r.IsDelete);

                if (room == null)
                {
                    _logger.LogWarning("添加患者住院登记失败：病房不存在，病房ID：{RoomId}", addDto.RoomId);
                    return new ApiResult<int> { msg = "病房不存在" };
                }

                // 验证病床是否存在
                var hospitalBed = await _context.HospitalBeds
                    .FirstOrDefaultAsync(hb => hb.HospitalId == addDto.HospitalId && !hb.IsDelete);

                if (hospitalBed == null)
                {
                    _logger.LogWarning("添加患者住院登记失败：病床不存在，病床ID：{HospitalId}", addDto.HospitalId);
                    return new ApiResult<int> { msg = "病床不存在" };
                }

                // 检查该病床是否已被占用
                var existingAdmission = await _context.PatientAdmissions
                    .FirstOrDefaultAsync(pa => pa.HospitalId == addDto.HospitalId && !pa.IsDelete);

                if (existingAdmission != null)
                {
                    _logger.LogWarning("添加患者住院登记失败：病床已被占用，病床ID：{HospitalId}", addDto.HospitalId);
                    return new ApiResult<int> { msg = "该病床已被占用" };
                }

                // 创建患者住院登记实体
                var patientAdmission = new PatientAdmission
                {
                    Patient = addDto.Patient,
                    DepartmentId = addDto.DepartmentId,
                    RoomId = addDto.RoomId,
                    HospitalId = addDto.HospitalId,
                    Prepayment = addDto.Prepayment,
                    ConditionDesc = addDto.ConditionDesc,
                    DrugContraindications = addDto.DrugContraindications,
                    AdmissionTime = DateTime.Now,
                    IsDelete = false
                };

                // 添加到数据库
                _context.PatientAdmissions.Add(patientAdmission);
                await _context.SaveChangesAsync();

                // 记录添加成功日志
                _logger.LogInformation("患者住院登记添加成功，登记ID：{AdmissionId}，患者卡号：{Patient}", 
                    patientAdmission.AdmissionId, addDto.Patient);

                var apiResult = new ApiResult<int>();
                apiResult.success(patientAdmission.AdmissionId, "患者住院登记添加成功");
                return apiResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加患者住院登记失败：系统异常 - {ErrorMessage}", ex.Message);
                return new ApiResult<int> { msg = $"添加患者住院登记失败：系统异常 - {ex.Message}" };
            }
        }

        /// <summary>
        /// 查询患者住院登记列表（包含关联表信息）
        /// </summary>
        /// <param name="roomNumber">房间号（可选）</param>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<PatientAdmissionDto>>> GetPatientAdmissionListAsync(string? roomNumber = null)
        {
            try
            {
                var query = from pa in _context.PatientAdmissions
                           join dept in _context.DepartmentInfos on pa.DepartmentId equals dept.DepartmentId
                           join room in _context.Rooms on pa.RoomId equals room.RoomId
                           join bed in _context.HospitalBeds on pa.HospitalId equals bed.HospitalId
                           where !pa.IsDelete && !dept.IsDelete && !room.IsDelete && !bed.IsDelete
                           select new PatientAdmissionDto
                           {
                               AdmissionId = pa.AdmissionId,
                               Patient = pa.Patient,
                               DepartmentId = pa.DepartmentId,
                               DepartmentName = dept.DepartmentName,
                               RoomId = pa.RoomId,
                               RoomNumber = room.RoomNumber,
                               HospitalId = pa.HospitalId,
                               HospitalName = bed.HospitalName,
                               Prepayment = pa.Prepayment,
                               ConditionDesc = pa.ConditionDesc,
                               DrugContraindications = pa.DrugContraindications,
                               AdmissionTime = pa.AdmissionTime
                           };

                // 如果提供了房间号，添加房间号过滤条件
                if (!string.IsNullOrWhiteSpace(roomNumber))
                {
                    query = query.Where(x => x.RoomNumber.Contains(roomNumber));
                    _logger.LogInformation("查询患者住院登记列表，房间号过滤条件：{RoomNumber}", roomNumber);
                }

                var result = await query.OrderByDescending(x => x.AdmissionTime).ToListAsync();

                var apiResult = new ApiResult<List<PatientAdmissionDto>>();
                var message = !string.IsNullOrWhiteSpace(roomNumber) 
                    ? $"查询患者住院登记成功（房间号：{roomNumber}），共找到 {result.Count} 条记录"
                    : $"查询患者住院登记成功，共找到 {result.Count} 条记录";
                apiResult.success(result, message);
                return apiResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询患者住院登记列表失败：系统异常 - {ErrorMessage}", ex.Message);
                return new ApiResult<List<PatientAdmissionDto>> { msg = $"查询患者住院登记列表失败：系统异常 - {ex.Message}" };
            }
        }

        /// <summary>
        /// 查找Room表数据（包含关联表信息）
        /// </summary>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<RoomDetailDto>>> GetRoomListAsync()
        {
            try
            {
                var query = from room in _context.Rooms
                           join dept in _context.DepartmentInfos on room.DepartmentId equals dept.DepartmentId
                           join roomType in _context.RoomTypes on room.RoomTypeId equals roomType.RoomTypeId
                           where !room.IsDelete && !dept.IsDelete && !roomType.IsDelete
                           select new RoomDetailDto
                           {
                               RoomId = room.RoomId,
                               RoomNumber = room.RoomNumber,
                               Floor = room.Floor,
                               DepartmentId = room.DepartmentId,
                               DepartmentName = dept.DepartmentName,
                               RoomTypeId = room.RoomTypeId,
                               RoomTypeName = roomType.RoomTypeName,
                               Number_beds = room.Number_beds,
                               Price = room.Price,
                               CreatedAt = room.CreatedAt
                           };

                var result = await query.OrderBy(x => x.RoomId).ToListAsync();

                var apiResult = new ApiResult<List<RoomDetailDto>>();
                apiResult.success(result, $"查询Room表数据成功，共找到 {result.Count} 条记录");
                return apiResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询Room表数据失败：系统异常 - {ErrorMessage}", ex.Message);
                return new ApiResult<List<RoomDetailDto>> { msg = $"查询Room表数据失败：系统异常 - {ex.Message}" };
            }
        }
        /// <summary>
        /// 查找病人查找
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<SearchregistrationDto>>> GetPatientAdmission(GetPatientAdmissionDto dto)
        {
            try
            {
                var res=new ApiResult<List<SearchregistrationDto>>();

                var patientAdmissioninfo = patientAdmission.Getlist().Where(x => x.IsDelete.Equals(false));//登记表
                var departmentInfose = departmentInfo.Getlist().Where(x => x.IsDelete.Equals(false));//科室
                var medicalCardRegistrationInfo= medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false));//用户
                var roomin= roominfo.Getlist().Where(x => x.IsDelete.Equals(false));//房间号
                var hospitalBedInfo= hospitalBed.Getlist().Where(x => x.IsDelete.Equals(false));//床位号

                var frrinfose= frrinfo.Getlist().Where(x => x.IsDelete.Equals(false));//费用



                if (!string.IsNullOrEmpty(dto.Patient))
                {
                    patientAdmissioninfo = patientAdmissioninfo.Where(x => x.Patient.Contains(dto.Patient));
                }

                if (!string.IsNullOrEmpty(dto.Name))
                {
                    medicalCardRegistrationInfo = medicalCardRegistrationInfo.Where(x => x.Name.Contains(dto.Name));
                }

                if (dto.DepartmentId!=null)
                {
                    patientAdmissioninfo = patientAdmissioninfo.Where(x => x.DepartmentId.Equals(dto.DepartmentId));
                }


                if (!string.IsNullOrEmpty(dto.RoomNumber))
                {
                    roomin = roomin.Where(x => x.RoomNumber.Contains(dto.RoomNumber));
                }


                if (dto.Floor!=null)
                {
                    roomin = roomin.Where(x => x.Floor.Equals(dto.Floor));
                }



                var linp = from a in patientAdmissioninfo
                           join b in medicalCardRegistrationInfo on a.Patient equals b.Card_number
                           join c in departmentInfose on a.DepartmentId equals c.DepartmentId
                           join d in roomin on a.RoomId equals d.RoomId
                           join e in hospitalBedInfo on a.HospitalId equals e.HospitalId
                           join f in frrinfose on a.AdmissionId equals f.AdmissionId
                           select new SearchregistrationDto()
                           {
                               AdmissionId=a.AdmissionId,
                               Patient=a.Patient,
                               Name=b.Name,
                               DepartmentId=a.DepartmentId,
                               DepartmentName=c.DepartmentName,
                               RoomId=a.RoomId,
                               RoomNumber=d.RoomNumber,
                               Floor=d.Floor,
                               HospitalId=a.HospitalId,
                               HospitalName=e.HospitalName,
                               Prepayment=a.Prepayment,
                               ConditionDesc=a.ConditionDesc,
                               DrugContraindications=a.DrugContraindications,
                               AdmissionTime=a.AdmissionTime,
                               Amount=f.Amount,
                               RemainingAmount=f.RemainingAmount,
                               UsageAmount=f.UsageAmount

                           };


                res.success(linp.ToList(), "查找病人成功");
                return res;





            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 实现付款查操作
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<FeeDTO>>> GetFee(GetFeeDto dto)
        {
            try
            {
                var res=new ApiResult<List<FeeDTO>>();

                var patientAdmissionse = patientAdmission.Getlist().Where(x => x.IsDelete.Equals(false));

                var departmentInfose = departmentInfo.Getlist().Where(x => x.IsDelete.Equals(false));//科室

                var medicalCardRegistrationInfo = medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false));//用户

                var frrinfose = frrinfo.Getlist().Where(x => x.IsDelete.Equals(false));

                if (!string.IsNullOrEmpty(dto.Patient))
                {
                    patientAdmissionse = patientAdmissionse.Where(x => x.Patient.Contains(dto.Patient));
                }


                var linp = from a in patientAdmissionse
                           join b in frrinfose on a.AdmissionId equals b.AdmissionId  
                           join c in departmentInfose on a.DepartmentId equals c.DepartmentId
                           join d in medicalCardRegistrationInfo on a.Patient equals d.Card_number
                           select new FeeDTO()
                           {
                               FeeId=b.FeeId,
                               AdmissionId=b.AdmissionId,
                               Patient=a.Patient,
                               DepartmentId=a.DepartmentId,
                               DepartmentName=c.DepartmentName,
                               Amount=b.Amount,
                               RemainingAmount=b.RemainingAmount,
                               UsageAmount=b.UsageAmount,
                               Name=d.Name

                           };

                res.success(linp.ToList(), "实现付款查操作成功");
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查找Medicine表信息
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>药品信息列表</returns>
        public async Task<ApiResult<List<MedicineDto>>> GetMedicine(GetMedicineDto dto)
        {
            try
            {
                var res = new ApiResult<List<MedicineDto>>();

                // 获取所有未删除的药品信息
                var medicineList = medicine.Getlist().Where(x => x.IsDelete.Equals(false));

                // 根据查询条件过滤
                if (!string.IsNullOrEmpty(dto.MedicineName))
                {
                    medicineList = medicineList.Where(x => x.MedicineName.Contains(dto.MedicineName));
                }

                if (!string.IsNullOrEmpty(dto.DrugType))
                {
                    medicineList = medicineList.Where(x => x.DrugType.Contains(dto.DrugType));
                }

                if (dto.AdmissionId.HasValue)
                {
                    medicineList = medicineList.Where(x => x.AdmissionId == dto.AdmissionId.Value);
                }

                // 转换为DTO
                var result = medicineList.Select(x => new MedicineDto
                {
                    MedicineId = x.MedicineId,
                    AdmissionId = x.AdmissionId,
                    MedicineName = x.MedicineName,
                    DrugType = x.DrugType,
                    FeeName = x.FeeName,
                    DosageForm = x.DosageForm,
                    Specification = x.Specification,
                    PurchasePrice = x.PurchasePrice,
                    SellingPrice = x.SellingPrice,
                    StockQuantity = x.StockQuantity,
                    StockUpperLimit = x.StockUpperLimit,
                    StockLowerLimit = x.StockLowerLimit,
                    ProductionDate = x.ProductionDate,
                    ExpirationDate = x.ExpirationDate,
                    Efficacy = x.Efficacy
                }).ToList();

                res.success(result, "查找药品信息成功");
                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查找药品信息时发生错误");
                throw;
            }
        }


        /// <summary>
        /// 查找病人查找
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<SearchregistrationresultsDto>>> Search_discharge_results(GetPatientAdmissiondischargeDto dto)
        {
            try
            {
                var res = new ApiResult<List<SearchregistrationresultsDto>>();

                var patientAdmissioninfo = patientAdmission.Getlist().Where(x => x.IsDelete.Equals(false)&&x.Status.Equals(false));//登记表
                var departmentInfose = departmentInfo.Getlist().Where(x => x.IsDelete.Equals(false));//科室
                var medicalCardRegistrationInfo = medicalCardRegistration.Getlist().Where(x => x.IsDelete.Equals(false));//用户
                var roomin = roominfo.Getlist().Where(x => x.IsDelete.Equals(false));//房间号
                var hospitalBedInfo = hospitalBed.Getlist().Where(x => x.IsDelete.Equals(false));//床位号

                var frrinfose = frrinfo.Getlist().Where(x => x.IsDelete.Equals(false));//费用
                var medicineinfo= medicine.Getlist().Where(x => x.IsDelete.Equals(false));//药品



                if (!string.IsNullOrEmpty(dto.Patient))
                {
                    patientAdmissioninfo = patientAdmissioninfo.Where(x => x.Patient.Contains(dto.Patient));
                }

                if (!string.IsNullOrEmpty(dto.Name))
                {
                    medicalCardRegistrationInfo = medicalCardRegistrationInfo.Where(x => x.Name.Contains(dto.Name));
                }

                

                var linp = from a in patientAdmissioninfo
                           join b in medicalCardRegistrationInfo on a.Patient equals b.Card_number
                           join c in departmentInfose on a.DepartmentId equals c.DepartmentId
                           join d in roomin on a.RoomId equals d.RoomId
                           join e in hospitalBedInfo on a.HospitalId equals e.HospitalId
                           join f in frrinfose on a.AdmissionId equals f.AdmissionId
                           join g in medicineinfo on a.AdmissionId equals g.AdmissionId
                           select new SearchregistrationresultsDto()
                           {
                               AdmissionId = a.AdmissionId,
                               Patient = a.Patient,
                               Name = b.Name,
                               DepartmentId = a.DepartmentId,
                               DepartmentName = c.DepartmentName,
                               RoomId = a.RoomId,
                               RoomNumber = d.RoomNumber,
                               Floor = d.Floor,
                               HospitalId = a.HospitalId,
                               HospitalName = e.HospitalName,
                               Prepayment = a.Prepayment,
                               ConditionDesc = a.ConditionDesc,
                               DrugContraindications = a.DrugContraindications,
                               AdmissionTime = a.AdmissionTime,
                               Amount = f.Amount,
                               RemainingAmount = f.RemainingAmount,
                               UsageAmount = f.UsageAmount,
                               MedicineName=g.MedicineName,
                               DrugType=g.DrugType,
                               FeeName=g.FeeName,
                               DosageForm=g.DosageForm,
                               Specification=g.Specification,
                               PurchasePrice=g.PurchasePrice,
                               SellingPrice=g.SellingPrice,
                               StockQuantity=g.StockQuantity,
                               ProductionDate=g.ProductionDate,
                               ExpirationDate=g.ExpirationDate,
                               Efficacy=g.Efficacy

                           };


                res.success(linp.ToList(), "查找病人成功");
                return res;





            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 提交出院实现
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> Submit_discharge(Submit_dischargeDto dto)
        {
            try
            {
                var res = new ApiResult();

                var info = await patientAdmission.GetValue(x => x.AdmissionId.Equals(dto.AdmissionId));

                if (info != null)
                {
                    info.Status = true;

                    var model = await patientAdmission.Update(info);
                    if (model > 0)
                    {
                        res.success("出院成功");
                    }
                }

                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
